package com.library.controller;

import com.alibaba.fastjson.JSON;
import com.library.dao.BookDao;
import com.library.dao.impl.BookDaoImpl;
import com.library.entity.BookInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/book/*")
public class BookServlet extends HttpServlet {
    private BookDao bookDao = new BookDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/book/", "");

        switch (action) {
            case "findAllList":
                findAllList(request, response);
                break;
            case "findById":
                findById(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String action = requestURI.replace("/api/book/", "");

        switch (action) {
            case "addBookSubmit":
                addBook(request, response);
                break;
            case "updateBookSubmit":
                updateBook(request, response);
                break;
            case "deleteBook":
                deleteBook(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    private void findAllList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取查询参数
        String name = request.getParameter("name");
        String isbn = request.getParameter("isbn");
        String typeIdStr = request.getParameter("typeId");
        System.out.println("name=" + name);
        System.out.println("isbn=" + isbn);
        System.out.println("typeId=" + typeIdStr);
        
        // 创建查询条件对象
        BookInfo bookInfo = new BookInfo();
        if (name != null && !name.isEmpty()) {
            bookInfo.setName(name);
        }
        if (isbn != null && !isbn.isEmpty()) {
            bookInfo.setIsbn(isbn);
        }
        if (typeIdStr != null && !typeIdStr.isEmpty()) {
            try {
                int typeId = Integer.parseInt(typeIdStr);
                bookInfo.setTypeId(typeId);
            } catch (NumberFormatException e) {
                // 忽略无效的typeId
            }
        }
        
        // 根据条件查询图书
        List<BookInfo> books;
        if (name != null || isbn != null || (typeIdStr != null && !typeIdStr.isEmpty())) {
            System.out.println("bookInfo=" + bookInfo.toString());
            books = bookDao.searchBooks(bookInfo);
        } else {
            books = bookDao.findAllList();
        }
        
        System.out.println("books=" + books);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", books);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void findById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("this is findById");
        int id = Integer.parseInt(request.getParameter("id"));
        BookInfo book = bookDao.findBookById(id);
        System.out.println("book="+book);
        Map<String, Object> result = new HashMap<>();
        if (book != null) {
            result.put("code", 0);
            result.put("data", book);
        } else {
            result.put("code", 1);
            result.put("msg", "图书不存在");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void addBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        BookInfo book = new BookInfo();
        setBookInfo(request, book);

        System.out.println("book="+book);
        Map<String, Object> result = new HashMap<>();
        int rows = bookDao.addBook(book);
        if (rows > 0) {
            result.put("code", 0);
            result.put("msg", "添加成功");
        } else {
            result.put("code", 1);
            result.put("msg", "添加失败");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void updateBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 读取请求体
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String jsonBody = sb.toString();

        // 使用 FastJSON 将 JSON 字符串转为 Map 或 BookInfo 对象
        Map<String, Object> params = JSON.parseObject(jsonBody, Map.class);

        // 获取 id 和其他字段
        Integer id = Integer.valueOf(params.get("id").toString());
        System.out.println("id=" + id); // 现在应该可以正常输出了

        BookInfo book = new BookInfo();
        book.setId(id);

        // 设置其他字段
        book.setName((String) params.get("name"));
        book.setIsbn((String) params.get("isbn"));
        book.setAuthor((String) params.get("author"));
        book.setPublish((String) params.get("publish"));
        book.setLanguage((String) params.get("language"));
        book.setIntroduction((String) params.get("introduction"));

        if (params.containsKey("typeId")) {
            book.setTypeId(Integer.valueOf(params.get("typeId").toString()));
        }

        if (params.containsKey("price")) {
            book.setPrice(Double.valueOf(params.get("price").toString()));
        }

        String pubDateStr = (String) params.get("publishDate");
        if (pubDateStr != null && !pubDateStr.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date pubDate = sdf.parse(pubDateStr);
                book.setPublishDate(pubDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        System.out.println("更新book=" + book);

        Map<String, Object> result = new HashMap<>();
        int rows = bookDao.updateBook(book);
        if (rows > 0) {
            result.put("code", 0);
            result.put("msg", "更新成功");
        } else {
            result.put("code", 1);
            result.put("msg", "更新失败");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void deleteBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("this is deleteBook");
        int id = Integer.parseInt(request.getParameter("ids"));
        System.out.println("id="+id);
        Map<String, Object> result = new HashMap<>();
        int rows = bookDao.deleteBook(id);
        if (rows > 0) {
            result.put("code", 0);
            result.put("msg", "删除成功");
        } else {
            result.put("code", 1);
            result.put("msg", "删除失败");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void setBookInfo(HttpServletRequest request, BookInfo book) {
        book.setName(request.getParameter("name"));
        book.setAuthor(request.getParameter("author"));
        book.setPublish(request.getParameter("publish"));
        book.setIsbn(request.getParameter("isbn"));
        book.setIntroduction(request.getParameter("introduction"));
        book.setLanguage(request.getParameter("language"));
        
        // 添加对price的null检查
        String priceStr = request.getParameter("price");
        if (priceStr != null && !priceStr.isEmpty()) {
            book.setPrice(Double.parseDouble(priceStr));
        }
        
        // 添加对typeId的null检查
        String typeIdStr = request.getParameter("typeId");
        if (typeIdStr != null && !typeIdStr.isEmpty()) {
            book.setTypeId(Integer.parseInt(typeIdStr));
        }

        // 将pubDate改为publishDate
        String pubDateStr = request.getParameter("pubDate");
        System.out.println("pubDate="+pubDateStr);
        if (pubDateStr != null && !pubDateStr.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date pubDate = sdf.parse(pubDateStr);
                book.setPublishDate(pubDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
}